package org.dromara.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.web.core.BaseService;
import org.dromara.demo.domain.DemoTree;
import org.dromara.demo.mapper.DemoTreeMapper;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 测试树表Service业务层处理
 *
 *
 * @date 2021-07-26
 */
// @DS("slave") // 切换从库查询
@RequiredArgsConstructor
@Service
public class TestTreeServiceImpl extends BaseService {

  private final DemoTreeMapper baseMapper;

  public DemoTree queryById(Long id) {
    return baseMapper.selectById(id);
  }

  // @DS("slave") // 切换从库查询
  public List<DemoTree> queryList(DemoTree bo) {
    LambdaQueryWrapper<DemoTree> lqw = buildQueryWrapper(bo);
    return baseMapper.selectList(lqw);
  }

  private LambdaQueryWrapper<DemoTree> buildQueryWrapper(DemoTree bo) {
    Map<String, Object> params = bo.getParams();
    LambdaQueryWrapper<DemoTree> lqw = Wrappers.lambdaQuery();
    lqw.like(StringUtils.isNotBlank(bo.getTreeName()), DemoTree::getTreeName, bo.getTreeName());
    lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
      DemoTree::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
    lqw.orderByAsc(DemoTree::getId);
    return lqw;
  }

  public Boolean insertByBo(DemoTree bo) {
    validEntityBeforeSave(bo);
    boolean flag = baseMapper.insert(bo) > 0;
    return flag;
  }

  public Boolean updateByBo(DemoTree bo) {
    validEntityBeforeSave(bo);
    return baseMapper.updateById(bo) > 0;
  }

  /**
   * 保存前的数据校验
   *
   * @param entity 实体类数据
   */
  private void validEntityBeforeSave(DemoTree entity) {
    //TODO 做一些数据校验,如唯一约束
  }

  public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
    if (isValid) {
      //TODO 做一些业务上的校验,判断是否需要校验
    }
    return baseMapper.deleteBatchIds(ids) > 0;
  }
}
